uni-app request封装

MuYan2024-06-02VueVueuni-app

该文档拦截配置主要基于 cli 项目

安装依赖

npm i luch-request json-bigint -S

新建文件

// utils/http/request.ts
import Request from "luch-request";
import JSONBIG from "json-bigint";
import { successHandler, errorHandler } from "./http-handler";

const config = {
  baseURL: "你的请求地址",
  timeout: 30000, //超时时长30秒,
  header: {
    "Content-Type": "application/json",
  },
  dataType: "string",
  withCredentials: true,
  forcedJSONParsing: false,
};

const http = new Request(config);

//请求拦截器
http.interceptors.request.use(
  (config: any) => {
    const token = "";
    if (token) {
      Object.assign(config, {
        header: {
          Authorization: `Bearer ${token}`,
        },
      });
    }

    if (config.method === "POST") {
      config.data = (JSON.stringify(config.data) as unknown) as Record<
        string,
        any
      >;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

const json = JSONBIG({ storeAsString: true });

// 响应拦截器
http.interceptors.response.use(
  (response: any) => {
    response.data = json.parse(response.rawData);
    return successHandler(response);
  },
  (error: any) => {
    // 未登录时清空缓存跳转
    if (error.statusCode == 401) {
      uni.clearStorageSync();
    }
    error.data = json.parse(error.rawData);
    return errorHandler(error);
  }
);

export default http;
// utils/http/http-handler.ts
const errorTips = (msg: string) => {
  uni.showToast({
    title: msg,
    duration: 2000,
    icon: "none",
  });
};

/**
 * 成功处理
 * @param result
 * @returns
 */
export function successHandler(result: any): Promise<any> {
  const {
    data: { code },
  } = result;
  switch (code) {
    case 200:
      return Promise.resolve(result.data);
    // 请求 error 情况
    default:
      errorTips(message);
      return Promise.reject(result.data);
  }
}

/**
 * 错误处理
 * @param err
 * @returns
 */
export function errorHandler(err: any) {
  const status = err?.response?.status;
  switch (status) {
    case 404:
      return Promise.reject(err);
    default:
      return Promise.reject(err);
  }
}

使用

import request from "@/utils/http/request";

// get 请求
request.get("/user/login", {
  params: { userName: "name", password: "123456" },
});

// post 请求
request.post("/user/login", { userName: "name", password: "123456" });

// upload 请求
http.upload("api/upload/img", {
  // #ifdef APP-PLUS || H5
  files: [], // 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。App、H5( 2.6.15+)
  // #endif
  name: "file", // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
  header: {} /* 会与全局header合并,如有同名属性,局部覆盖全局 */,
  filePath: "", // 要上传文件资源的路径。
  formData: {}, // HTTP 请求中其他额外的 form data
});
上次更新 2026/6/23 11:49:15
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.8